package Random;

import java.util.Random;

public class _59_SpiralMatrixII {
    //wrong answer, isn't the spiral matrix;
    /*public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        Random r = new Random();
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                int num = r.nextInt(n * n)+1;
                res[i][j] = num;
            }
        }
        return res;
    }*/
    public int[][] generateMatrix(int n) {
        int[] dr = new int[]{0, 1, 0, -1};
        int[] dc = new int[]{1, 0, -1, 0};
        int rpos = 0;
        int cpos = 0;
        int pos = 0;//0 is right, 1 is down, 2 is left, 3 is up.
        int count = 1;
        int total = n * n;
        int[][] res = new int[n][n];
        while (count <= total) {
            res[rpos][cpos] = count;
            if ((pos == 0 && (cpos + 1 == n || res[rpos][cpos + 1] != 0)) ||
                    (pos == 1 && (rpos + 1 == n || res[rpos + 1][cpos] != 0)) ||
                    (pos == 2 && (cpos - 1 == -1 || res[rpos][cpos - 1] != 0)) ||
                    (pos == 3 && (rpos - 1 == -1 || res[rpos - 1][cpos] != 0))
            ) {

                pos = (pos + 1) % 4;
            }
            rpos += dr[pos];
            cpos += dc[pos];
            count++;
        }
        return res;
    }
}
